//
//  MYGChatContentCell.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/1.
//

import UIKit
import SVGKit

class MYGChatContentCell: UITableViewCell {
    // MARK: - Property
    var model: MYGChatContentCellModel? {
        didSet {
            guard let model = model else {
                return
            }
            if let oldValue = oldValue, (oldValue.content == model.content && oldValue.attribute == model.attribute) {
                return
            }
            
            reloadLayout()
            
            
          
            
//            if model.avatar.contains("http") {
//                avatar.sd_setImage(with: URL(string: model.avatar))
//            } else {
//                if let data = UserDefaults.standard.data(forKey: model.avatar) {
//                    guard let svgImage = SVGKImage(data: data) else {
//                        return
//                    }
//                    
//                    self.avatar.image = svgImage.uiImage
//                } else {
//                    DispatchQueue.global().async {
//                        let url = URL(string: model.avatar)!
//                        guard let data = try? Data(contentsOf: url) else {
//                            return
//                        }
//                        
//                        UserDefaults.standard.setValue(data, forKey: model.avatar)
//                        UserDefaults.standard.synchronize()
//                        guard let svgImage = SVGKImage(data: data) else {
//                            return
//                        }
//                
//                        DispatchQueue.main.async {
//                            self.avatar.image = svgImage.uiImage
//                        }
//                    }
//                }
//            }
            
            if model.isLeft == false {
                self.avatar.sd_setImage(with: URL(string: MYGUserManager.user?.doctor.avatar), placeholderImage: UIImage(named: "resum_head"))
            }else {
                if model.avatar.contains("http") {
                    avatar.sd_setImage(with: URL(string: model.avatar))
                } else {
                    avatar.image = UIImage(named: "head")
                }
            }
            
            nameLabel.text = model.name
            
            if let attribute = model.attribute {
                contentLabel.text = ""
                contentLabel.attributedText = attribute
                contentLabel.rz.tapAction {[weak self] label, tapActionId, range in
                    self?.model?.labelAction[tapActionId]?()
                }
            } else {
                if model.content.contains("<img") {
                    contentLabel.text = ""
                    if let data = UserDefaults.standard.data(forKey: model.content), let attr = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSAttributedString.self], from: data) as? NSAttributedString {
                        self.contentLabel.attributedText = attr
                    } else {
                        DispatchQueue.global().async {
                            guard let data = model.content.data(using: .utf8), let attr = try? NSAttributedString(
                                data: data,
                                options: [
                                    .documentType: NSAttributedString.DocumentType.html,
                                    .characterEncoding: String.Encoding.utf8.rawValue
                                ],
                                documentAttributes: nil
                            ) else {
                                return
                            }
                            
                            do {
                                let data = try NSKeyedArchiver.archivedData(withRootObject: attr, requiringSecureCoding: true)
                                UserDefaults.standard.setValue(data, forKey: model.content)
                                UserDefaults.standard.synchronize()
                            } catch {
                                print("数据归档失败\(error)")
                            }
                            
                            DispatchQueue.main.async {
                                self.contentLabel.attributedText = attr
                                self.reloadAction?()
                            }
                        }
                    }
                } else {
                    contentLabel.attributedText = nil
                    contentLabel.text = model.content
                }
            }
        }
    }
    
    var reloadAction:(()->Void)?
    
    var withdrawAction: (()->Void)?
    var tapActionBlock: (()->Void)?
    // MARK: - init
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        configUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - UI
    private func configUI() {
        contentView.backgroundColor = .white
        contentView.addSubview(avatar)
        contentView.addSubview(nameLabel)
        contentView.addSubview(bgView)
        bgView.addSubview(contentLabel)
        
        reloadLayout()
    }
    
    private func reloadLayout() {
        guard let isLeft = model?.isLeft else {
            return
        }
        avatar.snp.remakeConstraints { make in
            if isLeft {
                make.left.equalToSuperview().offset(25)
            } else {
                make.right.equalToSuperview().inset(25)
            }
            make.top.equalToSuperview().offset(20)
            make.width.height.equalTo(36)
        }
        
        nameLabel.snp.remakeConstraints { make in
            if isLeft {
                make.left.equalTo(avatar.snp.right).offset(10)
            } else {
                make.right.equalTo(avatar.snp.left).offset(-10)
            }
            make.top.equalTo(avatar.snp.top)
        }
        
        bgView.snp.remakeConstraints { make in
            if isLeft {
                make.left.equalTo(avatar.snp.right).offset(10)
            } else {
                make.right.equalTo(avatar.snp.left).offset(-10)
            }
            make.width.lessThanOrEqualTo(205)
            make.top.equalTo(nameLabel.snp.bottom).offset(7)
            make.bottom.equalToSuperview().inset(5)
        }
        
        contentLabel.snp.remakeConstraints { make in
            make.left.right.equalToSuperview().inset(13)
            make.top.bottom.equalToSuperview().inset(8)
        }
    }
    
    // MARK: - lazy load
    private lazy var avatar: UIImageView = {
        let imgV = UIImageView()
        imgV.layer.masksToBounds = true
        imgV.layer.cornerRadius = 18
        return imgV
    }()
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(16)
        label.textColor = .rgba(38, 38, 40, 1)
        label.text = "系统"
        return label
    }()
    
    private(set) lazy var bgView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(247, 247, 247, 1)
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 4
        
        let longtap = UILongPressGestureRecognizer(target: self, action: #selector(showBack))
        view.isUserInteractionEnabled = true
        longtap.minimumPressDuration = 1.0
        view.addGestureRecognizer(longtap)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        view.addGestureRecognizer(tap)
        
        return view
    }()
    
    private lazy var contentLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(12)
        label.textColor = .rgba(51, 51, 51, 1)
        label.numberOfLines = 0
        return label
    }()
}

extension MYGChatContentCell {
    @objc
    private func showBack() {
        self.withdrawAction?()
    }
    
    @objc
    private func tapAction() {
        self.tapActionBlock?()
    }
    
}
